<template>
  <view class="chat-page">
    <!-- 顶部导航栏 -->
    <view class="header-bar">
      <view class="brand">SKILLITH</view>
      <view class="user-info">
        <image :src="getAvatarUrl(userStore.profile?.avatarUrl)" class="avatar" @error="handleAvatarError" />
        <text class="nickname">{{ userStore.profile?.nickname }}</text>
      </view>
    </view>

    <!-- 聊天室内容 -->
    <view class="chat-content">
      <view v-if="loading" class="loading-spinner">
        <span class="spinner"></span>
        <text>加载中...</text>
      </view>
      
      <view v-else-if="!isConnected" class="connection-status">
        <view class="status-icon">🔌</view>
        <text class="status-text">连接中...</text>
        <button class="retry-btn" @click="connectWebSocket">重试</button>
      </view>
      
      <view v-else class="chat-container">
        <!-- 快捷操作按钮 -->
        <view class="quick-actions">
          <button class="action-btn friends-btn" @click="goToFriends">
            <text class="btn-icon">👥</text>
            <text class="btn-text">我的好友</text>
          </button>
          <button class="action-btn mark-read-btn" @click="markAllAsRead">
            <text class="btn-icon">✓</text>
            <text class="btn-text">一键已读</text>
          </button>
        </view>

        <!-- 聊天记录 -->
        <view class="chat-history-section">
          <view class="section-header">
            <text class="section-title">最近聊天</text>
          </view>
          
          <view class="chat-list">
            <view 
              v-for="chat in recentChats" 
              :key="chat.other_user_id" 
              class="chat-item"
              @click="openChat(chat)"
            >
              <image :src="getAvatarUrl(chat.other_user_avatar)" class="chat-avatar" @error="handleChatAvatarError" />
              <view class="chat-info">
                <text class="chat-name">{{ chat.other_user_nickname }}</text>
                <text class="last-message">{{ chat.last_message }}</text>
              </view>
              <view class="chat-meta">
                <text class="last-time">{{ formatTime(chat.last_message_time) }}</text>
                <view v-if="chat.unread_count > 0" class="unread-badge">
                  {{ chat.unread_count }}
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { useUserStore } from '@/store/user'
import { getAvatarUrl } from '@/utils/imageUtils.js'

const userStore = useUserStore()

// 数据
const loading = ref(false)
const isConnected = ref(false)
const friends = ref([])
const recentChats = ref([])
const shouldReconnect = ref(true) // 是否应该重连

// WebSocket连接
let ws = null

// 初始化
onMounted(() => {
  initChat()
})

onShow(async () => {
  if (isConnected.value) {
    await loadFriends()
    await loadRecentChats()
  }
})

// 监听全局WebSocket消息
onMounted(() => {
  uni.$on('chatMessage', handleChatMessage)
  uni.$on('newMessage', (message) => {
    console.log('收到新消息事件（来自聊天详情页面）:', message)
    updateRecentChats(message)
  })
})

onUnmounted(() => {
  uni.$off('chatMessage', handleChatMessage)
  uni.$off('newMessage')
})

// 初始化聊天功能
const initChat = async () => {
  loading.value = true
  try {
    await connectWebSocket()
    await loadFriends()
    await loadRecentChats()
  } catch (error) {
    console.error('初始化聊天功能失败:', error)
    uni.showToast({
      title: '初始化失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 连接WebSocket（使用全局连接）
const connectWebSocket = () => {
  return new Promise((resolve, reject) => {
    console.log('使用全局WebSocket连接，无需创建新连接')
    isConnected.value = true
    resolve()
  })
}

// 处理聊天消息
const handleChatMessage = (data) => {
  console.log('收到聊天消息:', data)
  
  if (data.message) {
    console.log('处理新消息:', data.message)
    updateRecentChats(data.message)
  }
}

// 加载好友列表
const loadFriends = async () => {
  try {
    const token = uni.getStorageSync('accessToken')
    const response = await uni.request({
      url: '${NETWORK_CONFIG.API_BASE_URL}/friends',
      method: 'GET',
      header: {
        'Access-Token': `Bearer ${token}`
      }
    })
    
    if (response.data && response.data.success) {
      friends.value = response.data.data || []
    }
  } catch (error) {
    console.error('加载好友列表失败:', error)
  }
}

// 加载最近聊天
const loadRecentChats = async () => {
  try {
    const token = uni.getStorageSync('accessToken')
    console.log('加载最近聊天记录')
    
    const response = await uni.request({
      url: '${NETWORK_CONFIG.API_BASE_URL}/simple-chat/recent',
      method: 'GET',
      header: {
        'Access-Token': `Bearer ${token}`
      }
    })
    
    console.log('最近聊天响应:', response.data)
    
    if (response.data && response.data.code === 200) {
      recentChats.value = response.data.data || []
      console.log('最近聊天记录:', recentChats.value)
    } else {
      console.error('获取最近聊天失败:', response.data)
    }
  } catch (error) {
    console.error('加载最近聊天失败:', error)
  }
}

// 开始聊天
const startChat = (friend) => {
  uni.navigateTo({
    url: `/pages/social/chat-detail?userId=${friend.id}&name=${friend.nickname}`
  })
}

// 打开聊天
const openChat = async (chat) => {
  try {
    // 先标记该聊天为已读
    const token = uni.getStorageSync('accessToken')
    await uni.request({
      url: '${NETWORK_CONFIG.API_BASE_URL}/simple-chat/mark-read',
      method: 'POST',
      data: { otherUserId: chat.other_user_id },
      header: { 'Access-Token': `Bearer ${token}` }
    })
    
    // 更新本地未读数量
    chat.unread_count = 0
    
    // 跳转到聊天详情
    uni.navigateTo({
      url: `/pages/social/chat-detail?userId=${chat.other_user_id}&name=${chat.other_user_nickname}`
    })
  } catch (error) {
    console.error('标记已读失败:', error)
    // 即使标记失败也继续跳转
    uni.navigateTo({
      url: `/pages/social/chat-detail?userId=${chat.other_user_id}&name=${chat.other_user_nickname}`
    })
  }
}

// 跳转到好友页面
const goToFriends = () => {
  uni.navigateTo({
    url: '/pages/friends/index'
  })
}

// 一键已读
const markAllAsRead = async () => {
  try {
    const token = uni.getStorageSync('accessToken')
    
    // 调用后端批量标记已读API
    await uni.request({
      url: '${NETWORK_CONFIG.API_BASE_URL}/simple-chat/mark-all-read',
      method: 'POST',
      header: { 'Access-Token': `Bearer ${token}` }
    })
    
    // 重新加载最近聊天以获取最新的未读数量
    await loadRecentChats()
    
    uni.showToast({
      title: '已标记全部已读',
      icon: 'success'
    })
  } catch (error) {
    console.error('标记已读失败:', error)
    uni.showToast({
      title: '标记已读失败',
      icon: 'none'
    })
  }
}

// 更新最近聊天
const updateRecentChats = async (message) => {
  console.log('收到新消息，重新加载最近聊天:', message)
  
  // 重新从后端获取最新的聊天列表和未读数量
  await loadRecentChats()
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  const now = new Date()
  const diff = now - date
  
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
  return date.toLocaleDateString()
}

// 头像错误处理
const handleAvatarError = () => {
  console.log('用户头像加载失败')
}

const handleFriendAvatarError = () => {
  console.log('好友头像加载失败')
}

const handleChatAvatarError = () => {
  console.log('聊天头像加载失败')
}

// 组件卸载时关闭WebSocket
onUnmounted(() => {
  if (ws) {
    // 微信小程序中关闭WebSocket连接
    ws.close({
      code: 1000,
      reason: '页面关闭'
    })
  }
})
</script>

<style scoped>
.chat-page {
  background: #f5f5f5;
  min-height: 100vh;
}

.header-bar {
  background: #4A90E2;
  color: white;
  padding: 12px 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.brand {
  font-size: 20px;
  font-weight: bold;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  object-fit: cover;
}

.nickname {
  font-size: 14px;
  color: white;
}

.chat-content {
  padding: 16px;
}

.loading-spinner {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  gap: 16px;
}

.spinner {
  width: 32px;
  height: 32px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #4A90E2;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.connection-status {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  gap: 16px;
}

.status-icon {
  font-size: 48px;
}

.status-text {
  color: #666;
  font-size: 16px;
}

.retry-btn {
  background: #4A90E2;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
}

.chat-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.quick-actions {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.action-btn {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 16px 12px;
  border: none;
  border-radius: 12px;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s ease;
}

.action-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.friends-btn {
  background: linear-gradient(135deg, #4A90E2, #357ABD);
  color: white;
}

.mark-read-btn {
  background: linear-gradient(135deg, #4CAF50, #45A049);
  color: white;
}

.btn-icon {
  font-size: 24px;
}

.btn-text {
  font-size: 14px;
  font-weight: 600;
}

.friends-section,
.chat-history-section {
  background: white;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.add-friend-btn {
  background: #4A90E2;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 6px;
  font-size: 12px;
  cursor: pointer;
}

.friends-list,
.chat-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.friend-item,
.chat-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.friend-item:hover,
.chat-item:hover {
  background: #f8f9fa;
}

.friend-avatar,
.chat-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.friend-info,
.chat-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.friend-name,
.chat-name {
  font-weight: 600;
  color: #333;
  font-size: 14px;
}

.friend-status {
  font-size: 12px;
  color: #666;
}

.friend-status.online {
  color: #4CAF50;
}

.last-message {
  font-size: 12px;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.chat-meta {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4px;
}

.last-time {
  font-size: 12px;
  color: #999;
}

.unread-badge {
  background: #ff4757;
  color: white;
  border-radius: 10px;
  padding: 2px 6px;
  font-size: 10px;
  font-weight: 600;
  min-width: 16px;
  text-align: center;
}
</style>